<?php
namespace app\admin\controller;
use app\admin\model\Business as BusinessModel;
use app\admin\model\Message as MessageModel;
use app\admin\controller\Base;
use think\Db;
use think\Session;
use think\Loader;

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;


class Business extends Base
{
    
    public function lst()
    {
        //$list=BusinessModel::paginate(3);
        $field = [
            'bus.id'=>'bus_id',
            'bus.no'=>'bus_no',
            'bus.name'=>'bus_name',
            'bus.tel'=>'bus_tel',
            'bus.cate_id'=>'bus_cate_id',
            'bus.area_id'=>'bus_area_id',
            'bus.address'=>'bus_address',
            'bus.content'=>'bus_content',
            'bus.status'=>'bus_status',
            'bus.create_time'=>'bus_create_time',
            'bus.update_time'=>'bus_update_time',
            'cate.id'=>'cate_id',
            'cate.name'=>'cate_name',
            'area.id'=>'area_id',
            'area.name'=>'area_name'
        ];
        $list = db('business')
            ->alias('bus')
            ->field($field)
            ->join('area area','bus.area_id = area.id')
            ->join('category cate',' bus.cate_id = cate.id')
            ->order("bus.id DESC")
            ->paginate(15);
        $this->assign('list',$list);
        $category=db('category')->select();
        $this->assign('category',$category);
        return view();
    }

    public function add()
    {
        $category=db('category')->select();
        $area=db('area')->select();
        $this->assign('area',$area);
        $this->assign('category',$category);
        if (request()->isPost())
        {
            $id=rand(0,9999);
            $sn = date('Y', time()).date('m', time()).date('d', time());
            $sn.=sprintf("%04d", $id);
            $data=[
                'no'=>'YW'.$sn,
                'name'=>input('name'),
                'tel'=>input('tel'),
                'cate_id'=>input('cate_id'),
                'area_id'=>input('area_id'),
                'address'=>input('address'),
                'thumb'=>input('thumb'),
                'content'=>input('content'),
                'create_time'=>time(),
                'update_time'=>time(),
                'status'=>1
            ];




            $validate = \think\Loader::validate('Business');
            if (!$validate->scene('add')->check($data))
            {
                $this->error($validate->getError());die;
            }
            if (db('business')->insert($data))
        {
            return $this->success('业务添加成功','lst');
        }
        else
        {
            return $this->error('业务添加失败','lst');
        }
            return ;
        }
        return $this->fetch();
    }
    
    public function edit()
    {
        $id=input('id');
        $business=db('business')->find($id);
        if (request()->isPost())
        {
            $data=input('post.');

            $validate = \think\Loader::validate('Business');
            if (!$validate->scene('edit')->check($data))
            {
                $this->error($validate->getError());die;
            }

            $save=db('business')->where('id','=',$id)->update($data);
            if ($save!==false)
            {
                $this->success('修改业务成功','lst');
            }
            else {
                $this->error('修改业务失败','lst');
            }
        }
        
        
        $this->assign('business',$business);
        $area=db('area')->select();
        $this->assign('area',$area);
        $category=db('category')->select();
        $this->assign('category',$category);

        return $this->fetch();
    }
    
    public function del()
    {
        $id=input('id');

            if (db('business')->where('id','=',$id)->delete()){
                $this->success('业务删除成功','lst');
            }else {
                $this->error('业务删除失败','lst');
            }


    }

    public function search()
    {



        $field = [
            'bus.id'=>'bus_id',
            'bus.no'=>'bus_no',
            'bus.name'=>'bus_name',
            'bus.tel'=>'bus_tel',
            'bus.cate_id'=>'bus_cate_id',
            'bus.area_id'=>'bus_area_id',
            'address'=>input('address'),
            'bus.content'=>'bus_content',
            'bus.status'=>'bus_status',
            'bus.create_time'=>'bus_create_time',
            'bus.update_time'=>'bus_update_time',
            'cate.id'=>'cate_id',
            'cate.name'=>'cate_name',
            'area.id'=>'area_id',
            'area.name'=>'area_name'
        ];

        $keywords=input('keywords');//获取搜索关键词
        $class = input('sel');//获取搜索类型
        $map = ['bus.no','bus.name','bus.tel','cate.name','area.name'];
        if($keywords){
            if($class == 0){
                $sel[$map[0]] = $map[0];
                $sel[$map[0]]  = ['like','%'.$keywords.'%'];//关键词模糊搜索语句
            }elseif ($class==1){
                $sel[$map[1]] = $map[1];
                $sel[$map[1]]  = ['like','%'.$keywords.'%'];//关键词模糊搜索语句
            }
            elseif ($class==2){
                $sel[$map[2]] = $map[2];
                $sel[$map[2]]  = ['like','%'.$keywords.'%'];//关键词模糊搜索语句
            }
            elseif ($class==3){
                $sel[$map[3]] = $map[3];
                $sel[$map[3]]  = ['like','%'.$keywords.'%'];//关键词模糊搜索语句
            }
            elseif ($class==4){
                $sel[$map[4]] = $map[4];
                $sel[$map[4]]  = ['like','%'.$keywords.'%'];//关键词模糊搜索语句
            }
//            print_r($sel);exit;
            $list = db('business')
                ->alias('bus')
                ->field($field)
                ->join('area area','bus.area_id = area.id')
                ->join('category cate',' bus.cate_id = cate.id')
                ->where($sel)
                ->order("bus.id DESC")
                ->paginate(15);
            $this->assign('list',$list);
            $category=db('category')->select();
            $this->assign('category',$category);
            $this->assign('keywords',$keywords);
        }else{
            $this->assign('keywords','没有关键词');//没有关键词的情况处理
            $this->assign('list',null);

        }

        return view();
    }
    public function step($status)
    {

        $field = [
            'bus.id'=>'bus_id',
            'bus.no'=>'bus_no',
            'bus.name'=>'bus_name',
            'bus.tel'=>'bus_tel',
            'bus.cate_id'=>'bus_cate_id',
            'bus.address'=>'bus_address',
            'bus.content'=>'bus_content',
            'bus.status'=>'bus_status',
            'bus.create_time'=>'bus_create_time',
            'cate.id'=>'cate_id',
            'cate.name'=>'cate_name',
            'area.id'=>'area_id',
            'area.name'=>'area_name'

        ];
        if(Session::get('logininfo')['group_id']==2){
            $list = db('business')
                ->alias('bus')
                ->field($field)
                ->join('area area','bus.area_id = area.id')
                ->join('category cate',' bus.cate_id = cate.id')
                ->where('status',$status)
                ->where('pstatus',1)
                ->order("bus.id DESC")
                ->paginate(15);
            }
            elseif (Session::get('logininfo')['group_id']==13){
                $list = db('business')
                    ->alias('bus')
                    ->field($field)
                    ->join('area area','bus.area_id = area.id')
                    ->join('category cate',' bus.cate_id = cate.id')
                    ->where('status',$status)
                    ->where('area_id',Session::get('logininfo')['area_id'])
                    ->order("bus.id DESC")
                    ->paginate(15);
            }
        else{
            $list = db('business')
                ->alias('bus')
                ->field($field)
                ->join('area area','bus.area_id = area.id')
                ->join('category cate',' bus.cate_id = cate.id')
                ->where('status',$status)
                ->where('pstatus',1)
                ->order("bus.id DESC")
                ->paginate(15);
        }
        $this->assign('list',$list);
        $category=db('category')->select();
        $this->assign('category',$category);
        return view();
    }

    public function ajaxShow(){
        $input=input();

        $id=input('id');
        $message=db('message')->alias('mes')
            ->join('admin adm',' mes.user_id = adm.id')
            ->where("mes.business_id","=",$id)
            ->select();

        $field = [
            'bus.id'=>'bus_id',
            'bus.no'=>'bus_no',
            'bus.name'=>'bus_name',
            'bus.tel'=>'bus_tel',
            'bus.cate_id'=>'bus_cate_id',
            'bus.address'=>'bus_address',
            'bus.content'=>'bus_content',
            'bus.thumb'=>'bus_thumb',
            'bus.status'=>'bus_status',
            'pos.id'=>'pos_id',
            'pos.pname'=>'pos_name',
            'pos.level'=>'pos_level',
            'pos.pstatus'=>'pos_status',
            'area.id'=>'area_id',
            'area.name'=>'area_name'
        ];
        $re=db('business')->alias('bus')->Field($field)
            ->join('area area','bus.area_id = area.id')
            ->join('position pos',' bus.status = pos.level')
            ->where("bus.id","=",$id)
            ->find();

        $res['info']=$message;
//        foreach ($message as $k => $v){
//            $res['info'][$k]['content'] = strip_tags($v->content);
//            $res['info'][$k]['user_name']=db('admin')->field('name')->where('id','=',$res['info'][$k]['user_id']);
//        }
        $res['base']=$re;
        $res['base']['cate_name']=$input['cate_id'];

        return $this->returnjson(200,$res);
    }

    public function kanyan(){
        $field = [
            'bus.id'=>'bus_id',
            'bus.no'=>'bus_no',
            'bus.name'=>'bus_name',
            'bus.tel'=>'bus_tel',
            'bus.cate_id'=>'bus_cate_id',
            'bus.area_id'=>'bus_area_id',
            'bus.address'=>'bus_address',
            'bus.content'=>'bus_content',
            'bus.status'=>'bus_status',
            'bus.create_time'=>'bus_create_time',
            'bus.update_time'=>'bus_update_time',
            'cate.id'=>'cate_id',
            'cate.name'=>'cate_name',
            'area.id'=>'area_id',
            'area.name'=>'area_name'
        ];
        if(Session::get('logininfo')['group_id']==2){
            $where=[
                'status'=>1,
                'pstatus'=>0,
            ];
        }
        else{
            $where=[
                'status'=>1,
                'pstatus'=>0,
                'area_id'=>Session::get('logininfo')['area_id'],
            ];
        }

        $list = db('business')
            ->alias('bus')
            ->field($field)
            ->join('area area','bus.area_id = area.id')
            ->join('category cate',' bus.cate_id = cate.id')
            ->where($where)
            ->order("bus.id DESC")
            ->paginate(15);
        $this->assign('list',$list);

        return view();

    }

    public function ajaxBackkanyan(){
        $id=input('id');
        $business = model('Business');
        $data0=[
            'pstatus'=>0
        ];
        $res = $business->where('id', '=', $id)->setField($data0);

        return $this->returnjson(200,$res);

    }

    public function upimg(){
        $file=request()->file('thumb');
        $info=$file->move(ROOT_PATH . 'public/uploads');
        if($info){
            echo $info->getSaveName();
        }
        else{
            echo $file->geterror();
        }

    }

    public function savekanyan(){
        $id=input('id');
        $field = [
            'bus.id'=>'bus_id',
            'bus.no'=>'bus_no',
            'bus.name'=>'bus_name',
            'bus.tel'=>'bus_tel',
            'bus.cate_id'=>'bus_cate_id',
            'bus.area_id'=>'bus_area_id',
            'bus.address'=>'bus_address',
            'bus.content'=>'bus_content',
            'bus.status'=>'bus_status',
            'bus.create_time'=>'bus_create_time',
            'bus.update_time'=>'bus_update_time',
            'cate.id'=>'cate_id',
            'cate.name'=>'cate_name',
            'area.id'=>'area_id',
            'area.name'=>'area_name'
        ];

        $business = db('business')
            ->alias('bus')
            ->field($field)
            ->join('area area','bus.area_id = area.id')
            ->join('category cate',' bus.cate_id = cate.id')
            ->order("bus.id DESC")
            ->find($id);
        if (request()->isPost())
        {
            $data=[
           'thumb'=>input('thumb'),

        ];
            $thumb = '/uploads'.'/'.input('thumb');
            $data['thumb'] = $thumb;



            $save=db('business')->where('id','=',$id)->update($data);
            if ($save!==false)
            {
                $data0=[
                    'pstatus'=>1,

                ];
                $res = db('business')->where('id','=',$id)->update($data0);
                $this->success('上传勘验单成功','kanyan');
            }
            else {
                $this->error('上传勘验单失败','kanyan');
            }
        }


        $this->assign('business',$business);
        return view();

    }

    public function ajaxSavekanyan(){
        $input=input();
//
//        $business = model('Business');
//        $data=[
//            'thumb'=>input('thumb'),
//            'status'=>1,
//            'update_time'=>time(),
//        ];
//        if($_FILES['thumb']['tmp_name']) {
//            $file = request()->file('thumb');
//            $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');
//            if ($info) {
//                $thumb ='http://www.shenpi.com/' . 'public' . DS . 'uploads'.'/'.$info->getSaveName();
//                $data['thumb'] = $thumb;
//            }
//
//            $res = $business-> where('id','=',$input['id'])->setField($data);

 //       }
        $res=$input;
        return $this->returnjson(200,$res);

    }

    public function ajaxPass(){
        $input=input();

        $status=$input['status'];
        if($status==5) {
            $res['error']='该业务已终审通过，请勿重复审核';
        }
        else{
            $res=$input;
        }
        return $this->returnjson(200,$res);

    }

    public function ajaxYijian(){
        $input=input();
        $content=$input['content'];
        if($content==""){
            $content=="审核通过";
        }
        $data=[
            'user_id'=>Session::get('logininfo')['uid'],
            'business_id'=>input('id'),

            'content'=>$content,
            'mstatus'=>1,
            'create_time'=>time(),
            'position_name'=>input('pname'),

        ];
        $status=$input['status'];
        $business = model('Business');
        $msgres=db('message')->insert($data);
        if($msgres){
            if($status<5) {
                $data0=[
                    'status'=>$status+1,
                    'update_time'=>time(),
                ];
                $res = $business->where('id', '=', $input['id'])->setField($data0);
            }
            else{
                $res['error']='该业务已终审通过，请勿重复审核';
            }
        }
        return $this->returnjson(200,$res);

    }

    public function ajaxBack(){
        $input=input();

        $status=$input['status'];
       if($status==0) {
           $res['error']='非法操作';
            }
            else{
                $res=$input;
            }
        return $this->returnjson(200,$res);

    }

    public function ajaxAddMsg(){
        $input=input();
        $data=[
            'user_id'=>Session::get('logininfo')['uid'],
            'business_id'=>input('id'),

            'content'=>input('content'),
            'mstatus'=>0,
            'create_time'=>time(),
            'position_name'=>input('pname'),

        ];
        $status=$input['status'];
        $business = model('Business');
        $msgres=db('message')->insert($data);
        if($msgres){
            if($status>0) {
                $data0=[
                    'status'=>$status-1,
                    'update_time'=>time(),
                ];
                $res = $business->where('id', '=', $input['id'])->setField($data0);
            }
            else{
                $res['error']='非法操作';
            }
        }
        return $this->returnjson(200,$res);

    }

    public function countdays(){
        $field = [
            'bus.id'=>'bus_id',
            'bus.no'=>'bus_no',
            'bus.name'=>'bus_name',
            'bus.tel'=>'bus_tel',
            'bus.cate_id'=>'bus_cate_id',
            'bus.content'=>'bus_content',
            'bus.status'=>'bus_status',
            'bus.create_time'=>'bus_create_time',
            'cate.id'=>'cate_id',
            'cate.name'=>'cate_name',

        ];
        $map['status']=array(array('eq',1),array('eq',5),'OR');
        //今日统计

        $days['data'] = db('business')
            ->alias('bus')
            ->field($field)
            ->join('category cate',' bus.cate_id = cate.id')
            ->whereTime('update_time', 'd')
            ->whereTime('create_time', 'd')
            ->order("bus.id DESC")
            ->paginate(15);

        $dayss=model('Business')->whereTime('update_time', 'd')->select();
        $daycount=count($dayss);

        //已办结数
        $dayse=model('Business')->whereTime('update_time', 'd')->where('status',5)->select();
        $daycounte=count($dayse);
        $days['counte']=$daycounte;

        $days['count']=$daycount;
        $this->assign('days',$days);


        return view();

    }

    public function countweeks(){
        $field = [
            'bus.id'=>'bus_id',
            'bus.no'=>'bus_no',
            'bus.name'=>'bus_name',
            'bus.tel'=>'bus_tel',
            'bus.cate_id'=>'bus_cate_id',
            'bus.content'=>'bus_content',
            'bus.status'=>'bus_status',
            'bus.create_time'=>'bus_create_time',
            'cate.id'=>'cate_id',
            'cate.name'=>'cate_name',

        ];
        $map['status']=array(array('eq',1),array('eq',5),'OR');
        //本周统计
        $weeks['data'] = db('business')
            ->alias('bus')
            ->field($field)
            ->join('category cate',' bus.cate_id = cate.id')
            ->whereTime('update_time', 'w')
            ->whereTime('create_time', 'w')
            ->order("bus.id DESC")
            ->paginate(15);
        $weekss=model('Business')->whereTime('create_time', 'w')->order('id DESC')->select();
        $weekcount=count($weekss);
        $weeks['count']=$weekcount;
        //已办结数
        $weekse=model('Business')->whereTime('update_time', 'w')->where('status',5)->select();
        $weekcounte=count($weekse);
        $weeks['counte']=$weekcounte;
        $this->assign('weeks',$weeks);


        return view();

    }

    public function countmonth(){
        $field = [
            'bus.id'=>'bus_id',
            'bus.no'=>'bus_no',
            'bus.name'=>'bus_name',
            'bus.tel'=>'bus_tel',
            'bus.cate_id'=>'bus_cate_id',
            'bus.content'=>'bus_content',
            'bus.status'=>'bus_status',
            'bus.create_time'=>'bus_create_time',
            'cate.id'=>'cate_id',
            'cate.name'=>'cate_name',

        ];
        $map['status']=array(array('eq',1),array('eq',5),'OR');


        //本月统计
        $month['data'] = db('business')
            ->alias('bus')
            ->field($field)
            ->join('category cate',' bus.cate_id = cate.id')
            ->whereTime('update_time', 'm')
            ->whereTime('create_time', 'm')
            ->order("bus.id DESC")
            ->paginate(15);
        $months=model('Business')->whereTime('create_time', 'm')->select();
        $monthcount=count($months);
        $month['count']=$monthcount;
        //已办结数
        $monthe=model('Business')->whereTime('update_time', 'm')->where('status',5)->order('id DESC')->select();
        $monthcounte=count($monthe);
        $month['counte']=$monthcounte;
        $this->assign('month',$month);


        return view();

    }

    public function countyears(){
        $field = [
            'bus.id'=>'bus_id',
            'bus.no'=>'bus_no',
            'bus.name'=>'bus_name',
            'bus.tel'=>'bus_tel',
            'bus.cate_id'=>'bus_cate_id',
            'bus.content'=>'bus_content',
            'bus.status'=>'bus_status',
            'bus.create_time'=>'bus_create_time',
            'cate.id'=>'cate_id',
            'cate.name'=>'cate_name',

        ];
        $map['status']=array(array('eq',1),array('eq',5),'OR');

        //本年统计
        $years['data'] = db('business')
            ->alias('bus')
            ->field($field)
            ->join('category cate',' bus.cate_id = cate.id')
            ->whereTime('update_time', 'y')
            ->whereTime('create_time', 'y')
            ->order("bus.id DESC")
            ->paginate(15);
        $yearss=model('Business')->whereTime('create_time', 'y')->order('id DESC')->select();
        $yearscount=count($yearss);
        $years['count']=$yearscount;
        //已办结数
        $yearse=model('Business')->whereTime('update_time', 'y')->where('status',5)->select();
        $yearscounte=count($yearse);
        $years['counte']=$yearscounte;
        $this->assign('years',$years);

        return view();

    }

    public function sendMail(){
        $toemail = 'kefu@hczycm.com';//定义收件人的邮箱
        $mail = new PHPMailer();
        $mail->isSMTP();// 使用SMTP服务
        $mail->CharSet = "utf8";// 编码格式为utf8，不设置编码的话，中文会出现乱码
        $mail->Host = "smtp.qq.com";// 发送方的SMTP服务器地址
        $mail->SMTPAuth = true;// 是否使用身份验证
        $mail->Username = "sxhcxf@qq.com";// 发送方的QQ邮箱用户名，就是自己的邮箱名
        $mail->Password = "nojhunjylgcubjgj";// 发送方的邮箱密码，不是登录密码,是qq的第三方授权登录码,要自己去开启,在邮箱的设置->账户->POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务 里面
        $mail->SMTPSecure = "tls";// 使用ssl协议方式,
        $mail->Port = 587;// QQ邮箱的ssl协议方式端口号是465/587

        $mail->setFrom("sxhcxf@qq.com","正义传媒");// 设置发件人信息，如邮件格式说明中的发件人,
        $mail->addAddress($toemail,'');// 设置收件人信息，如邮件格式说明中的收件人
//        $mail->addReplyTo("xxxxx@qq.com","Reply");// 设置回复人信息，指的是收件人收到邮件后，如果要回复，回复邮件将发送到的邮箱地址
        //$mail->addCC("xxx@163.com");// 设置邮件抄送人，可以只写地址，上述的设置也可以只写地址(这个人也能收到邮件)
        //$mail->addBCC("xxx@163.com");// 设置秘密抄送人(这个人也能收到邮件)
        //$mail->addAttachment("bug0.jpg");// 添加附件

        $mail->Subject = "这是一个测试邮件";// 邮件标题
        $mail->Body = "您有新的业务待审核，请登录管理系统进行相关操作";// 邮件正文
        //$mail->AltBody = "This is the plain text纯文本";// 这个是设置纯文本方式显示的正文内容，如果不支持Html方式，就会用到这个，基本无用
        if(!$mail->send()){// 发送邮件
            echo "Message could not be sent.<br>";
            echo "Mailer Error: ".$mail->ErrorInfo;// 输出错误信息
        }else{
            echo '发送成功';
        }
    }

}
